﻿using AppDataStruct;
using ComLib.ComType;
using EECMISWS;
using FTPService;
using KWindow.KPageCore;
using LogLib;
using Newtonsoft.Json.Linq;
using System;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace YSLPages
{
    public partial class PageQueryPeopleInfo : PageControlBase
    {
       
        private bool _bCancellFlag = false;
        //private Stopwatch sw = new Stopwatch();

        private SFZInfo _sfz = new SFZInfo();

        private bool _queryResult = false;

        private PreApplyInfo _appInfo = null;

        private WebDataAccess _webAccess = null;

        private PictureBox pictureBox1 = null;

        private Image imgQuerying = null;

        private Image imgQueryFailed = null;

        private Label labelInputTip = null;

        public PageQueryPeopleInfo()
        {
            InitializeComponent();
            SetProcessBase(ProcessQueryPeopleInfo.Instance);
        }

        private void GetControls()
        {
            pictureBox1 = GetControl<PictureBox>("pictureBox1") as PictureBox;
            imgQueryFailed = GetImage("QueryFailed");
            imgQuerying = GetImage("Querying");
            labelInputTip = GetControl<Label>("labelInputTip") as Label;
           
        }

        //初始化窗体数据
        public override void InitCtrls()
        {
            base.InitCtrls();
            GetControls();         
        }

        //初始化窗体数据
        public override void InitData()
        {
            base.InitData();
            labelInputTip.Text = "正在查询中";
            labelInputTip.ForeColor = Color.White;
            _bCancellFlag = false;
            pictureBox1.Image = imgQuerying;
            _webAccess = WebDataAccess.Instance;
            _appInfo = new PreApplyInfo();
            _queryResult = false;
            _sfz = Process.GetValue<SFZInfo>("SFZInfo");
            if (UserAction == UserApplyAction.TakePhotoAndWeiYinTB
               || UserAction == UserApplyAction.TakePhotoAndYSL)
            {
                _appInfo.XCRX = Process.GetValue<string>("Liveportrait");
                _appInfo.ZZZPPATH = Process.GetValue<string>("ZZZPPath");
            }
            if (_sfz != null)
            {
                _appInfo.SFZH = _sfz.SFZH;
                _appInfo.ZWXM = _sfz.Name;
                _appInfo.CSRQ = _sfz.BirthDate;
                _appInfo.XB.Code = (_sfz.Sex == "男" ? "1" : "2");
            }
            else
            {
             
            }
        }

        private void SetTips(string content, bool isSuccess=true)
        {
            labelInputTip.Text = content;
            int w = labelInputTip.Width;
            int x = (this.Width - w) / 2;
            labelInputTip.Left = x;
            if (!isSuccess)
            {
                labelInputTip.ForeColor = Color.Red;
            }
            else
            {
                labelInputTip.ForeColor = Color.White;
            }
        }

        /// <summary>
        /// 保存窗体数据(窗体本次做完后, 进入下一步之前)
        /// </summary>
        public override void UpdateData()
        {
            Process.SetValue("SFZInfo", _sfz);
            Process.SetValue("PreApplyInfo", _appInfo);
            if(!Process.ContainsKey("PersonDataDirectory"))
            {
                string personDir = _config.OutputDirs[_appInfo.SFZH];
                Process.SetValue("PersonDataDirectory", personDir);
            }
        }

        /// <summary>
        /// 清理窗体数据(窗体本次做完后)
        /// </summary>
        public override void ClearData()
        {
            base.ClearData();
            _queryResult = false;
            _appInfo = null;
        }

        /// <summary>
        /// 窗体关闭时
        /// </summary>
        public override void Close()
        {
            base.Close();
        }

        public override void StartWork()
        {
            base.StartWork();
            BeginQuerying();
        }

        public override void StopWork()
        {
            base.StopWork();
        }

        public override void OnCountdownCompleted(object sender, EventArgs e)
        {
            _bCancellFlag = true;
            base.OnCountdownCompleted(sender, e);
        }

        protected override void btnBack_Click(object sender, EventArgs e)
        {
            base.btnBack_Click(sender, e);
        }

        protected override void btnNext_Click(object sender, EventArgs e)
        {
            base.btnNext_Click(sender, e);
        }

        protected override void btnCancel_Click(object sender, EventArgs e)
        {
            _bCancellFlag = true;
            AbortWork();
            base.btnCancel_Click(sender, e);
        }

        private void InitBaseButtons()
        {
            if (UserAction == UserApplyAction.TakePhotoAndWeiYinTB
                || UserAction == UserApplyAction.OnlyWeiYinTB
                || UserAction == UserApplyAction.TakePhotoAndYSL)
            {
                buttonCancel.Visible = false;
                buttonNext.Visible = false;
                buttonBack.Visible = false;
            }
            //else
            //{
            //    buttonHome.Visible = true;
            //    buttonNext.Visible = true;
            //    buttonLast.Visible = true;
            //}
        }

        private void BeginQuerying()
        {
            if (_sfz == null)
            {
                MessageBox.Show("无有效的身份证信息.");
                return;
            }
            WebDataAccess webAccess = WebDataAccess.Instance;
            if (!webAccess.Enabled)
            {
                MessageBox.Show("全国版接口未启用.");
                base.btnNext_Click(null, null);
                return;
            }
            Task.Factory.StartNew(() =>
            {
                //先从共享盘Z盘找照片
                if (GetPhoto())
                {
                    QueryPeopleInfo();
                }                
            });
        }

        private bool GetPhoto()
        {
            //string path = string.Format("Z:\\{0}\\{1}\\{2}.jpg", DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("dd"), _sfz.SFZH);
            //先从Z盘找
            //if (File.Exists(path))
            //{
            //    _appInfo.ZZZPPATH = path;
            //    Log.Write("找到照相机中的照片:"+path);
            //    return true;
            //}
            string photoDir = string.Format("D:\\Photo\\{0}\\{1}",DateTime.Now.ToString("yyyyMM"),DateTime.Now.ToString("dd"));
            if(!Directory.Exists(photoDir))
            {
                Directory.CreateDirectory(photoDir);
            }
            string photoLocalPath = string.Format("{0}\\{1}.jpg",photoDir,_sfz.SFZH);
            string photoRemotePath = string.Format("\\{0}\\{1}\\{2}.jpg",DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("dd"),_sfz.SFZH);
            string err="";
            //通过FTP下载照片
            FtpDownload ftp = new FtpDownload();
            if (ftp.DownloadFile(photoLocalPath, photoRemotePath, out err))
            {
                _appInfo.ZZZPPATH = photoLocalPath;
                return true;
            }
            else
            {
                Log.Write(err);
                OnQueryPhotoFailed();
                return false;
            }
            //Z盘没有找身份证照片
            //if (File.Exists(path))
            //{
            //    _appInfo.ZZZPPATH = "D:\\zp.bmp";
            //    Log.Write("使用身份证照片");
            //    return true;
            //}
            //如果都没有提示照相
            //MsgBox msg = new MsgBox("查询不到照片，请先到自助照相机拍照后再填表");
            //msg.Show(this);
            //MessageBox.Show("");
            //Log.Write("找不到照片:" + path);
            //OnQueryPhotoFailed();

            //return false;
        }
        private void QueryPeopleInfo()
        {
            JObject args = new JObject();
            args["SFZH"] = _sfz.SFZH;
            args["XM"] = _sfz.Name;
            args["CSRQ"] = _sfz.BirthDate;
            args["XB"] = _sfz.Sex;
            args["HasReadIDCard"] = _sfz.IsManualInputNumberVerify;
            if (!_webAccess.Inited)
            {
                if (!_webAccess.Login())
                {
                    OnQueryFailed(_webAccess.ErrorMessage);
                    return;
                }
            }
            PeopleQueryResult result = _webAccess.QueryPeopleInfo(args.ToString());
            if (!result.Success)
            {
                OnQueryFailed(_webAccess.ErrorMessage);
                return;
            }
            QueryPaperInfo();
            UpdatePeopleInfo(result);
            OnQueryCompleted();
            return;
        }

        private void QueryPaperInfo()
        {
            QueryPaperInfo result = _webAccess.QueryPaperInfo(_sfz.SFZH);
            if (result.Success)
            {
                Log.Write("查询本省有证件信息可更新");
                UpdatePaperInfo(result);
                return;
            }
            result = _webAccess.QueryQGPaperInfo(_sfz.SFZH);
            if (result.Success)
            {
                Log.Write("查询全国有证件信息可更新");
                UpdatePaperInfo(result);
                return;
            }
            else
            {
                Log.Write("查询全国无证件信息可更新");
            }
        }

        private void UpdatePaperInfo(QueryPaperInfo result)
        {            
            PaperInfo paperInfo = result.HZ;
            if (paperInfo != null && !string.IsNullOrEmpty(paperInfo.zjhm))
            {
                Log.Write(string.Format("HZ: zjhm={0}, yxrq={1}", paperInfo.zjhm, paperInfo.zjyxqz));
                _appInfo.HZSQ.ZJHM = paperInfo.zjhm;
                _appInfo.HZSQ.ZJYXQZ = paperInfo.zjyxqz;
                _appInfo.HZSQ.PaperStatus = paperInfo.zjzt;
            }
          
            paperInfo = result.SCZ;        
            if (paperInfo != null && !string.IsNullOrEmpty(paperInfo.zjhm))
            {
                Log.Write(string.Format("SCZ: zjhm={0}, yxrq={1}", paperInfo.zjhm, paperInfo.zjyxqz));
                _appInfo.SCZSQ.ZJHM = paperInfo.zjhm;
                _appInfo.SCZSQ.ZJYXQZ = paperInfo.zjyxqz;
                _appInfo.SCZSQ.PaperStatus = paperInfo.zjzt;
            }

            paperInfo = result.DLZ;         
            if (paperInfo != null && !string.IsNullOrEmpty(paperInfo.zjhm))
            {
                Log.Write(string.Format("DLZ: zjhm={0}, yxrq={1}", paperInfo.zjhm, paperInfo.zjyxqz));
                _appInfo.DLZSQ.ZJHM = paperInfo.zjhm;
                _appInfo.DLZSQ.ZJYXQZ = paperInfo.zjyxqz;
                _appInfo.DLZSQ.PaperStatus = paperInfo.zjzt;
            }
        }

        private void UpdatePeopleInfo(PeopleQueryResult result)
        {
            Log.Write("Update people info from query result...");
            QGRKInfo qgrkInfo = result.PersonInfo;
            CodeMapService service = CodeMapService.Instance;
            if (_appInfo == null)
            {
                _appInfo = new PreApplyInfo();
            }          
            _appInfo.XB.Code = qgrkInfo.XB_CODE;
            _appInfo.XB.Value = qgrkInfo.XB;
            _appInfo.YJDZ = qgrkInfo.ZZXZ; 
            _appInfo.MZ.Code = qgrkInfo.MZ_CODE;
            _appInfo.MZ.Value = qgrkInfo.MZ;
            _appInfo.ZWXM = qgrkInfo.XM;
            _appInfo.CSRQ = qgrkInfo.CSRQ;
            _appInfo.BSWS = qgrkInfo.SNSW;
                
            _appInfo.CSD.Code = qgrkInfo.CSD_CODE;             
            _appInfo.CSD.Value = qgrkInfo.CSD;         
            _appInfo.HKSZD.Code = qgrkInfo.HKSZD_CODE;
            _appInfo.HKSZD.Value = qgrkInfo.HKSZD;
            _sfz.Address = qgrkInfo.ZZXZ;
            _sfz.BirthDate = qgrkInfo.CSRQ;           
            _sfz.Name = qgrkInfo.XM;
            _sfz.Nation = qgrkInfo.MZ;
            _sfz.Nation_Code = qgrkInfo.MZ_CODE;
            _sfz.Sex = qgrkInfo.XB;
            _sfz.Sex_Code = qgrkInfo.XB_CODE;
            _sfz.SFZH = qgrkInfo.SFZH;
            if (_sfz.IsManualInputNumberVerify || File.Exists(_sfz.HeaderPicturePath))
            {
                _sfz.HeaderPicturePath = qgrkInfo.XPDZ;
            }
            //Process.SetValue("SFZInfo", info);
        }

        private void OnQueryCompleted()
        {
            if (_bCancellFlag)
                return;
            _queryResult = true;
            Log.Write("人口信息查询成功");
            Action handler = () =>
            {
                SetTips("人口信息查询成功");
                UpdateData();
                Process.ToNext();
            };
            this.Invoke(handler);
        }

        private void OnQueryFailed(string outParams)
        {
            if (_bCancellFlag)
                return;
            string msg = string.Format("人口信息查询失败: \n{0}", outParams);
            Log.Write(msg);
            Action<string> handler = (e) =>
            {
                pictureBox1.Image = imgQueryFailed;
                SetTips(msg, false);
                CountdownSecond = 5;
                StartCountdown();
            };
            this.Invoke(handler, msg);
        }

        private void OnQueryPhotoFailed()
        {
            if (_bCancellFlag)
                return;
            string msg = string.Format("查询不到照片\n请先到自助照相机拍照后再填表");
            Log.Write(msg);
            Action<string> handler = (e) =>
            {
                //pictureBox1.Image = imgQueryFailed;
                SetTips(msg,false);
                CountdownSecond = 5;
                StartCountdown();
            };
            this.Invoke(handler, msg);
        }
    }
}
